#include "recvdata.h"

//#define PARAM_CONTROL

RecvData::RecvData(QIODevice *outputDevice, QObject *parent)
    : QObject(parent),
      m_outputDevice(outputDevice)
{

}

RecvData::~RecvData()
{
    m_outputDevice->close();
    m_socket->close();
}

void RecvData::setOutputDevice(QIODevice *outputDevice)
{
    m_outputDevice = outputDevice;
}

void RecvData::slot_start()
{
    qDebug() << QThread::currentThread();
    QString dir = QApplication::applicationDirPath();
    QSettings settings(dir+"/config.ini", QSettings::IniFormat);
    int port = settings.value("Network/hostPort").toInt();
    QString ip = settings.value("Network/hostIP").toString();

    m_socket = new QUdpSocket;
    int ret = m_socket->bind(QHostAddress(ip), port);
    qDebug() << ip << port;
    if (!ret) {
        QString error =  QString("%1:%2 绑定失败, 原因: %3")
                            .arg(ip)
                            .arg(port)
                            .arg(m_socket->errorString());
        Q_EMIT signal_bindFailed(error);
    }

    connect(m_socket, &QUdpSocket::readyRead, this, &RecvData::slot_writeDataToOutput);
}

void RecvData::slot_hangUp()
{
    m_connectStatus = ConnectStatus::Disconnected;
}

void RecvData::slot_writeDataToOutput()
{
    QNetworkDatagram datagram = m_socket->receiveDatagram();
    int ret = analysisData(datagram.data());
    if (ret == 1)
        return;
    if (m_connectStatus != ConnectStatus::Connected)
        return;
    int writeSize = m_outputDevice->write(datagram.data());
    Q_UNUSED(writeSize)
}

QHostAddress RecvData::hostIP()
{
    auto list = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface interface, list) {
        if (interface.type() != QNetworkInterface::Ethernet)
            continue;

        if (interface.humanReadableName().contains("VMware"))
            continue;

        foreach (auto entry ,interface.addressEntries()) {
            if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
                return entry.ip();
        }
    }

    return QHostAddress();
}

int RecvData::analysisData(const QByteArray &data)
{
    if (data.size() > 30)
        return 0;
#ifdef PARAM_CONTROL
    auto list = data.split('^');
    if (m_connectStatus == 0 && list[0] == "#CALLREQUEST") {

    }
#else
    if (data == m_protocolManager.protocolContent(Protocol::CallRequest)) {
        m_connectStatus = ConnectStatus::Connected;
        Q_EMIT signal_callRequest();
    }

    if (data == m_protocolManager.protocolContent(Protocol::Accept)) {
        m_connectStatus = ConnectStatus::Connected;
        Q_EMIT signal_callResponse(0);
    }

    if (data == m_protocolManager.protocolContent(Protocol::Refuse)) {
        m_connectStatus = ConnectStatus::Disconnected;
        Q_EMIT signal_callResponse(1);
    }

    if (data == m_protocolManager.protocolContent(Protocol::HangUp)) {
        m_connectStatus = ConnectStatus::Disconnected;
        Q_EMIT signal_hangUp();
    }

    if (data == m_protocolManager.protocolContent(Protocol::Cancel)) {
        m_connectStatus = ConnectStatus::Disconnected;
        Q_EMIT signal_callCancel();
    }
#endif
    return 1;
}
